﻿using System;
using System.Collections.Generic;
using System.ServiceProcess;
using System.Text;
using System.IO;

using ET.WinService.Core;
using ET.WinService.Core.Utility;

namespace ET.WinService
{
    static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        static void Main()
        {
            try
            {
                ///CreateSetupBatFile();
                LocalLogger.WriteLocal("Begin Run WinService!");
                log4net.Config.XmlConfigurator.Configure(new Uri(ServerContext.Context.LogConfigFile));
                ServiceBase.Run(ServiceUtil.LoadServices(ServerContext.Context.ServiceConfigFile));
                LocalLogger.WriteLocal("Run WinService Complete!");
                
            }
            catch (Exception ex)
            {
                LocalLogger.WriteLocal(ex.Message);
                LocalLogger.WriteEvenLog(ex.Message);
            }
        }

        private static void CreateSetupBatFile()
        {
            try
            {
                string setupFilePath = Path.Combine(ServerContext.ExecutePath, "setup.debug.bat");
                string unSetupFilePath = Path.Combine(ServerContext.ExecutePath, "unsetup.debug.bat");
                string dotNetVersion = Environment.Version.ToString();
                IList<string> serviceName = ServiceUtil.GetServiceNames(ServerContext.Context.ServiceConfigFile);
  
                FileHelper.CreateFile(setupFilePath);
                FileHelper.CreateFile(unSetupFilePath);

                StringBuilder str=new StringBuilder();
                str.Append(@"%SystemRoot%\Microsoft.NET\Framework\v");
                str.Append(dotNetVersion.Substring(0,dotNetVersion.LastIndexOf('.')));
                str.Append(@"\InstallUtil.exe ET.WinService.exe");
                str.AppendLine();
                foreach (string name in serviceName)
                {
                    str.AppendLine(string.Format(@"net start {0}",name));
                }
                str.AppendLine("@pause");
                FileHelper.WriteText(setupFilePath, str.ToString());
                str.Clear();
                str.Append(@"%SystemRoot%\Microsoft.NET\Framework\v");
                str.Append(dotNetVersion.Substring(0, dotNetVersion.LastIndexOf('.')));
                str.Append(@"\InstallUtil.exe /u ET.WinService.exe");
                str.AppendLine();
                str.AppendLine("@pause");
                FileHelper.WriteText(unSetupFilePath, str.ToString());
            }
            catch (Exception ex)
            {
                LocalLogger.WriteLocal(ex.Message);
            }

        }
    }
}
